import pygame
import json
import math
import random
import os
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
from typing import List, Dict, Tuple, Optional
import threading
import time
import hashlib

# 导入现有模块
import greedy_solver
import dp_solver
import dp2_solver
from boss_visualization import BossVisualization
import puzzle_solver
import boss
from maze_generator import MazeGenerator

# 初始化pygame
pygame.init()

# 屏幕设置
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Maze Adventure Game")

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
GRAY = (128, 128, 128)
DARK_GRAY = (64, 64, 64)
LIGHT_BLUE = (173, 216, 230)
GOLD = (255, 215, 0)
BROWN = (139, 69, 19)

# 字体设置
font_large = pygame.font.Font(None, 48)
font_medium = pygame.font.Font(None, 36)
font_small = pygame.font.Font(None, 24)
font_title = pygame.font.Font(None, 72)

class GameState:
    MAIN_MENU = "main_menu"
    MAZE_SETUP = "maze_setup"
    GAME_START = "game_start"
    PLAYING = "playing"
    BOSS_BATTLE = "boss_battle"
    PUZZLE_SOLVING = "puzzle_solving"
    VICTORY = "victory"

class Button:
    def __init__(self, x, y, width, height, text, color=GRAY, text_color=WHITE):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        self.text_color = text_color
        self.font = font_medium
        self.hovered = False
    
    def draw(self, screen):
        color = LIGHT_BLUE if self.hovered else self.color
        pygame.draw.rect(screen, color, self.rect)
        pygame.draw.rect(screen, WHITE, self.rect, 2)
        
        text_surface = self.font.render(self.text, True, self.text_color)
        text_rect = text_surface.get_rect(center=self.rect.center)
        screen.blit(text_surface, text_rect)
    
    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.hovered = self.rect.collidepoint(event.pos)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                return True
        return False

class PuzzleVisualization:
    def __init__(self, clues, password_hash, limit=1000000, algorithm="method1"):
        self.clues = clues
        self.password_hash = password_hash
        self.limit = limit
        self.algorithm = algorithm  # 选择的解密算法
        self.current_step = 0
        self.total_steps = 0
        self.found_password = None
        self.current_attempt = "000"
        self.progress = 0.0
        self.is_solving = False
        self.is_complete = False
        self.solving_thread = None
        
    def start_solving(self):
        """开始解密过程"""
        if not self.is_solving:
            self.is_solving = True
            self.solving_thread = threading.Thread(target=self._solve_with_progress)
            self.solving_thread.start()
    
    def _solve_with_progress(self):
        """带进度的解密过程，使用puzzle_solver.py中的算法"""
        try:
            # 根据选择的算法调用对应的解密函数
            if self.algorithm == "method1":
                steps, password = puzzle_solver.solve_password(self.clues, self.password_hash, self.limit)
            elif self.algorithm == "method2":
                steps, password = puzzle_solver.solve_password2(self.clues, self.password_hash, self.limit)
            elif self.algorithm == "method3":
                steps, password = puzzle_solver.solve_password3(self.clues, self.password_hash, self.limit)
            elif self.algorithm == "method4":
                steps, password = puzzle_solver.solve_password4(self.clues, self.password_hash, self.limit)
            elif self.algorithm == "method5":
                steps, password = puzzle_solver.solve_password5(self.clues, self.password_hash, self.limit)
            else:
                # 默认使用方法1
                steps, password = puzzle_solver.solve_password(self.clues, self.password_hash, self.limit)
            
            # 模拟进度更新以便用户观看
            if steps != -1 and password:
                # 模拟逐步解密过程
                for i in range(min(steps, 100)):  # 最多显示100步进度
                    if not self.is_solving:  # 如果停止解密则退出
                        break
                    self.current_step = int(i * steps / 100)
                    self.progress = i / 100
                    self.current_attempt = f"{random.randint(0,9)}{random.randint(0,9)}{random.randint(0,9)}"
                    time.sleep(0.05)  # 模拟解密时间
                
                # 设置最终结果
                self.current_step = steps
                self.total_steps = steps
                self.found_password = password
                self.current_attempt = password
                self.progress = 1.0
                self.is_complete = True
            else:
                self.total_steps = -1
                self.is_complete = True
                
        except Exception as e:
            print(f"解密过程出错: {e}")
            self.total_steps = -1
            self.is_complete = True
        
        self.is_solving = False
    
    def draw(self, screen, background=None):
        """绘制解密界面"""
        if background:
            screen.blit(background, (0, 0))
        else:
            screen.fill(BLACK)
        
        # 标题
        title_text = font_title.render("Password Decrypting...", True, GOLD)
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, 100))
        screen.blit(title_text, title_rect)
        
        # 显示算法信息
        algo_text = font_medium.render(f"Algorithm: {self.algorithm.upper()}", True, LIGHT_BLUE)
        screen.blit(algo_text, (50, 150))
        
        # 显示线索
        clues_text = font_medium.render("Clues:", True, WHITE)
        screen.blit(clues_text, (50, 200))
        
        for i, clue in enumerate(self.clues):
            clue_str = str(clue)
            clue_text = font_small.render(clue_str, True, YELLOW)
            screen.blit(clue_text, (50, 230 + i * 30))
        
        # 当前尝试的密码
        attempt_text = font_large.render(f"Current Try: {self.current_attempt}", True, WHITE)
        screen.blit(attempt_text, (400, 250))
        
        # 进度条
        progress_width = 400
        progress_height = 30
        progress_x = 400
        progress_y = 300
        
        # 进度条背景
        pygame.draw.rect(screen, DARK_GRAY, (progress_x, progress_y, progress_width, progress_height))
        
        # 进度条前景
        if self.progress > 0:
            filled_width = int(progress_width * self.progress)
            color = GREEN if self.is_complete else BLUE
            pygame.draw.rect(screen, color, (progress_x, progress_y, filled_width, progress_height))
        
        pygame.draw.rect(screen, WHITE, (progress_x, progress_y, progress_width, progress_height), 2)
        
        # 进度文字
        progress_text = font_medium.render(f"Progress: {self.progress:.1%}", True, WHITE)
        screen.blit(progress_text, (progress_x, progress_y + 40))
        
        # 尝试次数
        steps_text = font_medium.render(f"Attempts: {self.current_step}", True, WHITE)
        screen.blit(steps_text, (progress_x, progress_y + 70))
        
        # 完成状态
        if self.is_complete:
            success_text = font_large.render("Decryption Success!", True, GREEN)
            success_rect = success_text.get_rect(center=(SCREEN_WIDTH//2, 450))
            screen.blit(success_text, success_rect)
            
            password_text = font_medium.render(f"Password: {self.found_password}", True, GOLD)
            password_rect = password_text.get_rect(center=(SCREEN_WIDTH//2, 500))
            screen.blit(password_text, password_rect)
            
            total_text = font_medium.render(f"Total Attempts: {self.total_steps}", True, WHITE)
            total_rect = total_text.get_rect(center=(SCREEN_WIDTH//2, 530))
            screen.blit(total_text, total_rect)
            
            continue_text = font_small.render("Press SPACE to continue", True, WHITE)
            continue_rect = continue_text.get_rect(center=(SCREEN_WIDTH//2, 580))
            screen.blit(continue_text, continue_rect)

class MazeGame:
    def __init__(self):
        self.state = GameState.MAIN_MENU
        self.maze_data = None
        self.maze = None
        self.boss_visualization = None
        self.puzzle_visualization = None
        
        # 游戏状态
        self.player_pos = None
        self.game_path = []
        self.current_path_index = 0
        self.collected_resources = []
        self.total_score = 0
        self.solved_passwords = []
        self.move_timer = 0
        self.move_delay = 30  # 移动延迟（帧）
        self.selected_algorithm = "greedy"  # 默认使用贪心算法
        self.selected_puzzle_algorithm = "method1"  # 默认使用解密方法1
        
        # 记录已访问的特殊位置
        self.visited_boss_positions = set()
        self.visited_locker_positions = set()
        
        # 加载背景图片
        self.background = None
        self.load_background()
        
        # 创建按钮
        self.create_buttons()
        
        # 可视化参数
        self.cell_size = 35  # 增大格子以便更好显示字母
        self.maze_offset_x = 50
        self.maze_offset_y = 100
    
    def load_background(self):
        """加载背景图片"""
        try:
            # 尝试加载背景图片
            self.background = pygame.image.load("background.png")
            self.background = pygame.transform.scale(self.background, (SCREEN_WIDTH, SCREEN_HEIGHT))
            print("Background image loaded successfully")
        except (pygame.error, FileNotFoundError):
            print("Background image not found, creating default forest background")
            # 创建森林主题的默认背景
            self.background = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            
            # 创建渐变天空背景（从深蓝到浅蓝）
            for y in range(SCREEN_HEIGHT):
                if y < SCREEN_HEIGHT * 0.7:  # 天空部分
                    # 夜空渐变：从深蓝紫色到深蓝色
                    ratio = y / (SCREEN_HEIGHT * 0.7)
                    r = int(25 + ratio * 15)  # 25 -> 40
                    g = int(25 + ratio * 25)  # 25 -> 50  
                    b = int(40 + ratio * 30)  # 40 -> 70
                    color = (r, g, b)
                else:  # 地面部分
                    # 深绿色地面
                    color = (20, 35, 20)
                pygame.draw.line(self.background, color, (0, y), (SCREEN_WIDTH, y))
            
            # 添加一些"树木"剪影效果
            tree_color = (15, 25, 15)
            for i in range(0, SCREEN_WIDTH, 100):
                # 随机树木高度
                tree_height = random.randint(100, 200)
                tree_width = random.randint(30, 60)
                tree_x = i + random.randint(-20, 20)
                tree_y = SCREEN_HEIGHT - tree_height
                
                # 绘制树干
                trunk_width = tree_width // 4
                trunk_height = tree_height // 3
                pygame.draw.rect(self.background, (20, 15, 10), 
                               (tree_x + tree_width//2 - trunk_width//2, 
                                SCREEN_HEIGHT - trunk_height, 
                                trunk_width, trunk_height))
                
                # 绘制树冠（多个重叠的椭圆）
                for j in range(3):
                    crown_y = tree_y + j * (tree_height // 6)
                    crown_size = tree_width - j * 10
                    pygame.draw.ellipse(self.background, tree_color,
                                      (tree_x + (tree_width - crown_size)//2, 
                                       crown_y, crown_size, crown_size//2))

    def create_buttons(self):
        """创建界面按钮"""
        self.buttons = {
            'generate_maze': Button(400, 300, 200, 60, "Generate Maze"),
            'import_maze': Button(400, 400, 200, 60, "Import Maze"),
            'start_game': Button(500, 600, 200, 60, "Start Game", GREEN),
            'back_to_menu': Button(50, 50, 150, 45, "Back to Menu", RED),
            'greedy_algo': Button(100, 500, 120, 40, "Greedy", BLUE),
            'dp_algo': Button(230, 500, 120, 40, "DP-1", PURPLE),
            'dp2_algo': Button(360, 500, 120, 40, "DP-2", ORANGE),
            # 解密算法选择按钮
            'puzzle_method1': Button(100, 550, 80, 30, "M1", GRAY),
            'puzzle_method2': Button(190, 550, 80, 30, "M2", GRAY),
            'puzzle_method3': Button(280, 550, 80, 30, "M3", GRAY),
            'puzzle_method4': Button(370, 550, 80, 30, "M4", GRAY),
            'puzzle_method5': Button(460, 550, 80, 30, "M5", GRAY),
        }
    
    def show_maze_setup_dialog(self):
        """显示迷宫设置对话框"""
        root = tk.Tk()
        root.withdraw()
        
        # 获取迷宫大小
        size = simpledialog.askinteger("Maze Setup", "Enter maze size (7-20, must be odd):", minvalue=7, maxvalue=20)
        if not size:
            return None
        
        # 确保是奇数
        if size % 2 == 0:
            size += 1
            messagebox.showinfo("Info", f"Size adjusted to {size} (must be odd)")
        
        try:
            # 使用MazeGenerator生成迷宫
            generator = MazeGenerator(size)
            maze = generator.generate_maze()
            
            # 获取密码
            password = simpledialog.askstring("Password Setup", "Enter 3-digit password:")
            if not password or len(password) != 3 or not password.isdigit():
                messagebox.showerror("Error", "Password must be 3 digits")
                return None
            
            # 获取线索（简化版）
            clues_str = simpledialog.askstring("Clues Setup", 
                "Enter clues (JSON format), e.g.: [[5,-1,-1], [1,1]]")
            try:
                clues = json.loads(clues_str) if clues_str else [[5,-1,-1], [1,1]]
            except:
                clues = [[5,-1,-1], [1,1]]  # default clues
            
            # 生成密码哈希
            import hashlib
            password_hash = hashlib.sha256(password.encode()).hexdigest()
            
            # 生成Boss数据
            boss_data = [random.randint(10, 20) for _ in range(4)]
            
            # 生成技能数据
            skills = [[8, 4], [6, 3], [10, 5], [12, 6]]
            
            return {
                "maze": maze,
                "B": boss_data,
                "PlayerSkills": skills,
                "C": clues,
                "L": password_hash
            }
        
        except Exception as e:
            messagebox.showerror("Error", f"Failed to generate maze: {e}")
            return None
    

    def import_maze_file(self):
        """导入迷宫文件"""
        root = tk.Tk()
        root.withdraw()
        
        file_path = filedialog.askopenfilename(
            title="Select Maze File",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    maze_data = json.load(f)
                return maze_data
            except Exception as e:
                messagebox.showerror("Error", f"Cannot load file: {e}")
        
        return None
    
    def start_game_logic(self):
        """开始游戏逻辑"""
        if not self.maze_data:
            return
        
        # 初始化迷宫
        self.maze = [row[:] for row in self.maze_data["maze"]]
        
        # 找到起始位置
        for i in range(len(self.maze)):
            for j in range(len(self.maze[0])):
                if self.maze[i][j] == 'S':
                    self.player_pos = (i, j)
                    break
            if self.player_pos:
                break
        
        # 使用选定的算法生成路径
        self.game_path = self.run_selected_algorithm()
        self.collected_resources = []
        self.total_score = 0
        
        self.current_path_index = 0
        self.state = GameState.PLAYING
    
    def run_selected_algorithm(self):
        """运行选定的路径规划算法"""
        if not self.maze or not self.player_pos:
            return []
        
        try:
            if self.selected_algorithm == "greedy":
                # 使用贪心算法
                path = greedy_solver.solve_maze_treasure_hunt(self.maze)
                return path
            elif self.selected_algorithm == "dp":
                # 使用动态规划算法1
                score, path = dp_solver.solve_maze_combined_state(self.maze)
                self.total_score = score
                return path
            elif self.selected_algorithm == "dp2":
                # 使用动态规划算法2
                score, path = dp2_solver.solve_maze_all_items(self.maze)
                self.total_score = score
                return path
            else:
                # 默认使用贪心算法
                path = greedy_solver.solve_maze_treasure_hunt(self.maze)
                return path
        except Exception as e:
            print(f"算法执行错误: {e}")
            return [self.player_pos] if self.player_pos else []
    
    def update_game(self):
        """更新游戏状态"""
        if self.state == GameState.PLAYING:
            # AI自动移动
            self.move_timer += 1
            if self.move_timer >= self.move_delay:
                self.move_timer = 0
                
                if self.current_path_index < len(self.game_path) - 1:
                    self.current_path_index += 1
                    self.player_pos = self.game_path[self.current_path_index]
                    
                    # 检查当前位置的元素
                    if self.maze_data and self.player_pos:
                        current_cell = self.maze_data["maze"][self.player_pos[0]][self.player_pos[1]]
                        
                        if current_cell == 'B':
                            # 触发Boss战（只在第一次访问时）
                            if self.player_pos not in self.visited_boss_positions:
                                self.visited_boss_positions.add(self.player_pos)
                                self.boss_visualization = BossVisualization(self.maze_data)
                                self.state = GameState.BOSS_BATTLE
                        elif current_cell == 'L':
                            # 触发解密（只在第一次访问时）
                            if (self.player_pos not in self.visited_locker_positions and 
                                "C" in self.maze_data and "L" in self.maze_data):
                                self.visited_locker_positions.add(self.player_pos)
                                self.puzzle_visualization = PuzzleVisualization(
                                    self.maze_data["C"], 
                                    self.maze_data["L"],
                                    algorithm=self.selected_puzzle_algorithm
                                )
                                self.puzzle_visualization.start_solving()
                                self.state = GameState.PUZZLE_SOLVING
                        elif current_cell == 'E' and self.current_path_index != len(self.game_path)-1:
                            # 到达终点
                            self.state = GameState.VICTORY
        
        elif self.state == GameState.BOSS_BATTLE:
            if self.boss_visualization:
                self.boss_visualization.update()
                if self.boss_visualization.game_state == "victory":
                    # Boss战胜利，返回游戏
                    self.state = GameState.PLAYING
                    self.boss_visualization = None
        
        elif self.state == GameState.PUZZLE_SOLVING:
            if self.puzzle_visualization:
                # 只有在解密真正完成且不再处理中时才返回游戏状态
                if (self.puzzle_visualization.is_complete and 
                    not self.puzzle_visualization.is_solving and
                    self.puzzle_visualization.found_password):
                    # 解密完成，记录结果
                    self.solved_passwords.append({
                        'password': self.puzzle_visualization.found_password,
                        'steps': self.puzzle_visualization.total_steps
                    })
                    # 延迟2秒后返回游戏状态，让玩家看到结果
                    if not hasattr(self, 'puzzle_complete_timer'):
                        self.puzzle_complete_timer = 0
                    self.puzzle_complete_timer += 1
                    if self.puzzle_complete_timer >= 120:  # 2秒（60fps * 2）
                        self.state = GameState.PLAYING
                        self.puzzle_visualization = None
                        del self.puzzle_complete_timer
    
    def draw_maze(self, screen):
        """绘制迷宫"""
        if not self.maze or not self.maze_data:
            return
        
        # 计算3x3视野
        vision_cells = set()
        if self.player_pos:
            px, py = self.player_pos
            for dx in range(-1, 2):
                for dy in range(-1, 2):
                    nx, ny = px + dx, py + dy
                    if 0 <= nx < len(self.maze) and 0 <= ny < len(self.maze[0]):
                        vision_cells.add((nx, ny))
        
        # 绘制迷宫网格
        for i in range(len(self.maze)):
            for j in range(len(self.maze[0])):
                x = self.maze_offset_x + j * self.cell_size
                y = self.maze_offset_y + i * self.cell_size
                
                cell = self.maze_data["maze"][i][j]
                
                # 判断是否在视野内
                in_vision = (i, j) in vision_cells
                
                # 选择基础颜色（显示完整迷宫）
                if cell == '#':
                    color = BLACK
                elif cell == 'S':
                    color = GREEN
                elif cell == 'E':
                    color = RED
                elif cell == 'G':
                    color = GOLD
                elif cell == 'T':
                    color = PURPLE
                elif cell == 'B':
                    color = ORANGE
                elif cell == 'L':
                    color = BROWN
                else:
                    color = WHITE
                
                # 绘制基础格子
                pygame.draw.rect(screen, color, (x, y, self.cell_size, self.cell_size))
                
                # 3x3视野高亮边框
                if in_vision:
                    pygame.draw.rect(screen, LIGHT_BLUE, (x, y, self.cell_size, self.cell_size), 3)
                else:
                    pygame.draw.rect(screen, GRAY, (x, y, self.cell_size, self.cell_size), 1)
                
                # 在格子中心绘制字母标识
                if cell in ['S', 'E', 'G', 'T', 'B', 'L']:
                    text_surface = font_small.render(cell, True, WHITE if cell != 'G' else BLACK)
                    text_rect = text_surface.get_rect(center=(x + self.cell_size//2, y + self.cell_size//2))
                    screen.blit(text_surface, text_rect)
                
                # 绘制玩家
                if self.player_pos and (i, j) == self.player_pos:
                    pygame.draw.circle(screen, BLUE, 
                                     (x + self.cell_size//2, y + self.cell_size//2), 
                                     self.cell_size//3)
    
    def draw_ui(self, screen):
        """绘制游戏UI"""
        # 计算当前收集的金币数量
        collected_gold = 0
        total_gold = 0
        
        # 计算迷宫中的总金币数
        if self.maze_data and self.maze_data.get("maze"):
            for row in self.maze_data["maze"]:
                for cell in row:
                    if cell == 'G':
                        total_gold += 1
        
        # 计算已经走过路径中的金币数
        if self.game_path and self.maze_data:
            for i in range(min(self.current_path_index + 1, len(self.game_path))):
                x, y = self.game_path[i]
                if self.maze_data["maze"][x][y] == 'G':
                    collected_gold += 1
        
        # 得分信息
        score_text = font_medium.render(f"Score: {self.total_score}", True, WHITE)
        screen.blit(score_text, (SCREEN_WIDTH - 200, 50))
        
        # 收集信息
        collected_text = font_small.render(f"Gold: {collected_gold}/{total_gold}", True, WHITE)
        screen.blit(collected_text, (SCREEN_WIDTH - 200, 80))
        
        # 算法信息
        algo_text = font_small.render(f"Path Algo: {self.selected_algorithm.upper()}", True, WHITE)
        screen.blit(algo_text, (SCREEN_WIDTH - 200, 110))
        
        # 解密算法信息
        puzzle_algo_text = font_small.render(f"Puzzle Algo: {self.selected_puzzle_algorithm.upper()}", True, WHITE)
        screen.blit(puzzle_algo_text, (SCREEN_WIDTH - 200, 130))
        
        # 解密信息
        if self.solved_passwords:
            puzzle_text = font_small.render(f"Decrypted: {len(self.solved_passwords)}", True, WHITE)
            screen.blit(puzzle_text, (SCREEN_WIDTH - 200, 160))
        
        # 当前位置
        if self.player_pos:
            pos_text = font_small.render(f"Position: {self.player_pos}", True, WHITE)
            screen.blit(pos_text, (SCREEN_WIDTH - 200, 190))
        
        # 当前路径进度
        if self.game_path:
            progress_text = font_small.render(f"Progress: {self.current_path_index}/{len(self.game_path)-1}", True, WHITE)
            screen.blit(progress_text, (SCREEN_WIDTH - 200, 220))
        
        # 视野提示
        vision_text = font_small.render("Blue border: 3x3 Vision Range", True, LIGHT_BLUE)
        screen.blit(vision_text, (50, 50))
    
    def draw_victory_screen(self, screen):
        """绘制胜利界面"""
        if self.background:
            screen.blit(self.background, (0, 0))
        else:
            screen.fill(BLACK)
        
        # 胜利标题
        victory_text = font_title.render("VICTORY!", True, GOLD)
        victory_rect = victory_text.get_rect(center=(SCREEN_WIDTH//2, 150))
        screen.blit(victory_text, victory_rect)
        
        # 统计信息
        stats_y = 250
        
        # 总分
        score_text = font_large.render(f"Final Score: {self.total_score}", True, WHITE)
        score_rect = score_text.get_rect(center=(SCREEN_WIDTH//2, stats_y))
        screen.blit(score_text, score_rect)
        
        # 收集的资源
        stats_y += 60
        resources_text = font_medium.render(f"Resources Collected: {len(self.collected_resources)}", True, WHITE)
        resources_rect = resources_text.get_rect(center=(SCREEN_WIDTH//2, stats_y))
        screen.blit(resources_text, resources_rect)
        
        # 解密信息
        if self.solved_passwords:
            stats_y += 60
            for i, pwd_info in enumerate(self.solved_passwords):
                pwd_text = font_small.render(
                    f"Password {i+1}: {pwd_info['password']} ({pwd_info['steps']} attempts)", 
                    True, YELLOW
                )
                pwd_rect = pwd_text.get_rect(center=(SCREEN_WIDTH//2, stats_y + i * 30))
                screen.blit(pwd_text, pwd_rect)
        
        # 返回菜单提示
        menu_text = font_medium.render("Press ESC to return to main menu", True, WHITE)
        menu_rect = menu_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT - 100))
        screen.blit(menu_text, menu_rect)
    
    def draw(self, screen):
        """绘制当前状态"""
        if self.state == GameState.MAIN_MENU:
            if self.background:
                screen.blit(self.background, (0, 0))
            else:
                screen.fill(BLACK)
            
            # 标题
            title_text = font_title.render("Maze Adventure Game", True, GOLD)
            title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, 200))
            screen.blit(title_text, title_rect)
            
            # 绘制按钮
            self.buttons['generate_maze'].draw(screen)
            self.buttons['import_maze'].draw(screen)
        
        elif self.state == GameState.MAZE_SETUP:
            if self.background:
                screen.blit(self.background, (0, 0))
            else:
                screen.fill(BLACK)
            
            title_text = font_large.render("Maze Loaded", True, WHITE)
            title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, 250))
            screen.blit(title_text, title_rect)
            
            # 算法选择提示
            algo_title = font_medium.render("Select Algorithm:", True, WHITE)
            algo_rect = algo_title.get_rect(center=(SCREEN_WIDTH//2, 450))
            screen.blit(algo_title, algo_rect)
            
            # 当前选择的算法
            current_algo = font_small.render(f"Path Algorithm: {self.selected_algorithm.upper()}", True, GOLD)
            current_rect = current_algo.get_rect(center=(SCREEN_WIDTH//2, 480))
            screen.blit(current_algo, current_rect)
            
            # 解密算法选择提示
            puzzle_title = font_small.render("Puzzle Algorithm:", True, WHITE)
            puzzle_rect = puzzle_title.get_rect(center=(320, 530))
            screen.blit(puzzle_title, puzzle_rect)
            
            # 当前选择的解密算法
            current_puzzle = font_small.render(f"Current: {self.selected_puzzle_algorithm.upper()}", True, GOLD)
            current_puzzle_rect = current_puzzle.get_rect(center=(320, 590))
            screen.blit(current_puzzle, current_puzzle_rect)
            
            # 绘制按钮
            self.buttons['start_game'].draw(screen)
            self.buttons['back_to_menu'].draw(screen)
            self.buttons['greedy_algo'].draw(screen)
            self.buttons['dp_algo'].draw(screen)
            self.buttons['dp2_algo'].draw(screen)
            # 绘制解密算法选择按钮
            self.buttons['puzzle_method1'].draw(screen)
            self.buttons['puzzle_method2'].draw(screen)
            self.buttons['puzzle_method3'].draw(screen)
            self.buttons['puzzle_method4'].draw(screen)
            self.buttons['puzzle_method5'].draw(screen)
        
        elif self.state == GameState.PLAYING:
            if self.background:
                screen.blit(self.background, (0, 0))
            else:
                screen.fill(BLACK)
            self.draw_maze(screen)
            self.draw_ui(screen)
            self.buttons['back_to_menu'].draw(screen)
        
        elif self.state == GameState.BOSS_BATTLE:
            if self.boss_visualization:
                self.boss_visualization.draw(screen)
        
        elif self.state == GameState.PUZZLE_SOLVING:
            if self.puzzle_visualization:
                self.puzzle_visualization.draw(screen, self.background)
        
        elif self.state == GameState.VICTORY:
            self.draw_victory_screen(screen)
    
    def handle_event(self, event):
        """处理事件"""
        if self.state == GameState.MAIN_MENU:
            if self.buttons['generate_maze'].handle_event(event):
                maze_data = self.show_maze_setup_dialog()
                if maze_data:
                    self.maze_data = maze_data
                    self.state = GameState.MAZE_SETUP
            
            elif self.buttons['import_maze'].handle_event(event):
                maze_data = self.import_maze_file()
                if maze_data:
                    self.maze_data = maze_data
                    self.state = GameState.MAZE_SETUP
        
        elif self.state == GameState.MAZE_SETUP:
            if self.buttons['start_game'].handle_event(event):
                self.start_game_logic()
            elif self.buttons['back_to_menu'].handle_event(event):
                self.state = GameState.MAIN_MENU
                self.maze_data = None
            elif self.buttons['greedy_algo'].handle_event(event):
                self.selected_algorithm = "greedy"
            elif self.buttons['dp_algo'].handle_event(event):
                self.selected_algorithm = "dp"
            elif self.buttons['dp2_algo'].handle_event(event):
                self.selected_algorithm = "dp2"
            elif self.buttons['puzzle_method1'].handle_event(event):
                self.selected_puzzle_algorithm = "method1"
            elif self.buttons['puzzle_method2'].handle_event(event):
                self.selected_puzzle_algorithm = "method2"
            elif self.buttons['puzzle_method3'].handle_event(event):
                self.selected_puzzle_algorithm = "method3"
            elif self.buttons['puzzle_method4'].handle_event(event):
                self.selected_puzzle_algorithm = "method4"
            elif self.buttons['puzzle_method5'].handle_event(event):
                self.selected_puzzle_algorithm = "method5"
        
        elif self.state == GameState.PLAYING:
            if self.buttons['back_to_menu'].handle_event(event):
                self.state = GameState.MAIN_MENU
                self.reset_game()
        
        elif self.state == GameState.BOSS_BATTLE:
            if self.boss_visualization:
                self.boss_visualization.handle_event(event)
        
        elif self.state == GameState.PUZZLE_SOLVING:
            if event.type == pygame.KEYDOWN:
                if (event.key == pygame.K_SPACE and 
                    self.puzzle_visualization and 
                    self.puzzle_visualization.is_complete):
                    self.state = GameState.PLAYING
        
        elif self.state == GameState.VICTORY:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.state = GameState.MAIN_MENU
                    self.reset_game()
    
    def reset_game(self):
        """重置游戏状态"""
        self.maze_data = None
        self.maze = None
        self.boss_visualization = None
        self.puzzle_visualization = None
        self.player_pos = None
        self.game_path = []
        self.current_path_index = 0
        self.collected_resources = []
        self.total_score = 0
        self.solved_passwords = []
        self.visited_boss_positions = set()
        self.visited_locker_positions = set()

def main():
    """主函数"""
    clock = pygame.time.Clock()
    game = MazeGame()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            else:
                game.handle_event(event)
        
        # 更新游戏状态
        game.update_game()
        
        # 绘制
        game.draw(screen)
        pygame.display.flip()
        
        # 控制帧率
        clock.tick(60)
    
    pygame.quit()

if __name__ == "__main__":
    main() 